package com.L.yygh.user.Service.impl;

import com.L.yygh.common.exception.YyghException;
import com.L.yygh.common.result.ResultCodeEnum;
import com.L.yygh.enums.AuthStatusEnum;
import com.L.yygh.helper.JwtHelper;
import com.L.yygh.model.user.Patient;
import com.L.yygh.model.user.UserInfo;
import com.L.yygh.user.Service.PatientService;
import com.L.yygh.user.Service.UserInfoService;
import com.L.yygh.user.mapper.UserInfoMapper;
import com.L.yygh.vo.user.LoginVo;
import com.L.yygh.vo.user.UserAuthVo;
import com.L.yygh.vo.user.UserInfoQueryVo;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    //用户手机号登录接口
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //1.从loginVo中获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //2.判断手机号和验证码是否为空
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //3.判断手机验证码和输入的验证码是否一致
        String confirmCode = redisTemplate.opsForValue().get(phone);
        if(!code.equals(confirmCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxOpenId(loginVo.getOpenid());
            if(null != userInfo) {
                if(this.selectByPhone(loginVo.getPhone())!=null){
                    throw new YyghException(ResultCodeEnum.DATA_ERROR);
                }else if(userInfo.getPhone()==null) {
                    userInfo.setPhone(loginVo.getPhone());
                    this.updateById(userInfo);
                }else{

                }
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //userInfo=null 说明手机应当直接登录
        if(userInfo == null){
            //4.判断是否第一次登录，根据手机号查询数据库，如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            userInfo = baseMapper.selectOne(wrapper);
            if(null == userInfo){
                //第一次，添加到数据库中
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }else{
                //校验是否被禁用
                if(userInfo.getStatus()==0){
                    throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
                }

                //5.不是第一次，直接登录

            }
        }

        //6.返回登录信息
        //返回登录用户名
        //返回token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //使用生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;



    }

    @Override
    public UserInfo selectWxOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public UserInfo selectByPhone(String phone) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询出用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置用户的信息

        //认证人的姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        //userInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus(); //用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //用户状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();  //结束时间
//        System.out.println("createTimeBegin："+createTimeBegin);
//        System.out.println("createTimeEnd："+createTimeEnd);

        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }

        //调用mapper中的方法进行非空判断
        Page<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage, wrapper);
//        System.out.println("Page<UserInfo> userInfoPage1 ："+userInfoPage1);
//        System.out.println("UserInfo ："+userInfoPage1.getRecords().get(0));

        //编号变成对应的值
        userInfoPage1.getRecords().stream().forEach(item->{
            this.packetUserInfo(item);
        });
        return userInfoPage1;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0||status.intValue() == 1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        this.packetUserInfo(userInfo);
        map.put("userInfo",userInfo);

        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList",patientList);

        return map;
    }

    @Override
    public void approval(Integer userId, Integer authStatus) {
        //认证审批：2通过，-1不通过
        if(authStatus.intValue()==2||authStatus.intValue()==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }

    }

    private UserInfo packetUserInfo(UserInfo item) {
        //处理认证状态编码
        item.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
        //处理用户状态0/1
        String statusString = item.getStatus().intValue()==0?"锁定":"正常";
        item.getParam().put("statusString",statusString);
        return item;
    }
}
